<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\models;

/**
 * 菜单服务类
 * @author cleverstone
 * @since ym2.0
 */
class SystemMenuService
{
    /**
     * 菜单树
     * @return array
     */
    public static function tree()
    {
        $data = SystemMenu::query()->orderBy(['sort' => SORT_ASC])->all();
        return self::getTreeRecursive($data);
    }

    /**
     * 数据递归
     * @param array $data 菜单
     * @param int $pid 父ID
     * @return array
     */
    public static function getTreeRecursive($data, $pid = 0)
    {
        $result = [];
        foreach ($data as $i => $item) {
            if ($item['pid'] == $pid) {
                unset($data[$i]);

                $item['children'] = self::getTreeRecursive($data, $item['id']);
                $result[] = $item;
            }
        }

        return $result;
    }
}